import pymysql

class Conn:

    def __init__(self, user, passwd, host, db, port=3306):
        self.config = {
            "user": user,
            "password": passwd,
            "host": host,
            "database": db,
            "port": port,
            "charset": "utf8"
        }

    def __get_cur(self):
        """获取游标对象"""
        self.conn = pymysql.connect(**self.config)
        self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

    def execute(self, sql='', num="all"):
        self.__get_cur()

        sql = sql.strip()  # 去除左右两侧的空格
        try:
            self.cur.execute(sql)
            method = sql[:6]
            if method.upper() == "SELECT":
                if num == "all":
                    datas = self.cur.fetchall()
                else:
                    datas = self.cur.fetchone()
                print("sql执行成功!")
                return datas
            else:
                self.conn.commit()
                print("sql执行成功!")
                return True
        except Exception as e:
            self.conn.rollback()

        finally:
            self.close()
            print("数据库连接对象关闭成功")

    def close(self):
        self.cur.close()
        self.conn.close()

if __name__ == '__main__':
    conn = Conn("root", "diama_239", "192.168.1.239", "iconductor_media")
    datas = conn.execute('select * from teacher_basic_info where teacher_name = "李元芳";', "one")
    print(datas)
